import logging
from logging.handlers import TimedRotatingFileHandler
import os

class Logger:
    def __init__(self, name: str = "INTELLIBENCH", level: int = logging.INFO, log_dir: str = "logs"):
        self.logger = logging.getLogger(name)
        if not self.logger.handlers:
            # 确保日志目录存在
            os.makedirs(log_dir, exist_ok=True)
            log_path = os.path.join(log_dir, "app.log")
            # 按天分割日志，保留30天
            handler = TimedRotatingFileHandler(
                log_path, when="midnight", interval=1, backupCount=30, encoding="utf-8"
            )
            formatter = logging.Formatter(
                "[%(asctime)s] [%(levelname)s] %(name)s: %(message)s"
            )
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
            # 控制台也输出
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)
        self.logger.setLevel(level)

    def debug(self, msg: str, *args, **kwargs):
        self.logger.debug(msg, *args, **kwargs)

    def info(self, msg: str, *args, **kwargs):
        self.logger.info(msg, *args, **kwargs)

    def warning(self, msg: str, *args, **kwargs):
        self.logger.warning(msg, *args, **kwargs)

    def error(self, msg: str, *args, **kwargs):
        self.logger.error(msg, *args, **kwargs)

    def set_level(self, level: int):
        self.logger.setLevel(level)

# 单例
logger = Logger() 